<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId" :isPropagation="false">
    <template v-slot:common>
      <div class="wb-upload" :data-id="item.id" @click.stop ref="upload">
        <van-uploader
          v-model="fileList"
          :max-count="uploadCount"
          :max-size="maxsize"
          :accept="accept"
          :deletable="isDisplayDeleteBtn"
          @oversize="onOversize"
          @delete="onDelete"
          :before-read="onBeforeRead"
          :after-read="onAfterRead"
        >
        <template v-slot:default v-if="item.commonAttr.imgUrl" >
          <img :src="item.commonAttr.imgUrl" class="uploader-bg"/>
        </template>
        </van-uploader>
        <span class="need-cls font-size-24" v-show="item.commonAttr.need">*</span>
      </div>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { canvasUploadImg } from "@/components/utils/canvas-upload-img"
import { ref } from 'vue'
import { getCompIdByParam } from '@/plugins/utils'
import { CONTROL_TYPES } from '@/common/const-wb'
import { isHasOwnProperty } from '@/plugins/utils'
import { getPxOVwByValue } from '@/store/utils'

export default {
  name: "WbUpload",
  mixins: [utils, canvasUploadImg],
  setup (props) {
    return {
      maxsize: 1024 * 1024 * parseFloat(props.item.commonAttr.uploadLimitSize),
      minsize: 1024 * 1024 * 0.2,
      accept: "image/png,image/jpeg",
      // uploadLoading: {
      //   url: "https://img.yzcdn.cn/vant/leaf.jpg",
      //   status: "uploading",
      //   message: "上传中...",
      // },
      // uploadFail: {
      //   url: "https://img.yzcdn.cn/vant/tree.jpg",
      //   status: "failed",
      //   message: "上传失败",
      // },
      fileList: ref([]),
      fileUrls: {},
      fileNames: [],
    };
  },
  components: {
    InjectTemplate,
  },
  created() {
    let docStyle = document.documentElement.style;
    if(this.uploadCount > 1) {
      docStyle.setProperty(`--van-uploader-w-size`, getPxOVwByValue(this.item.conAttr.height));
      docStyle.setProperty(`--van-uploader-h-size`, getPxOVwByValue(this.item.conAttr.height));
    } else {
      docStyle.setProperty(`--van-uploader-w-size`, getPxOVwByValue(this.item.conAttr.width));
      docStyle.setProperty(`--van-uploader-h-size`, getPxOVwByValue(this.item.conAttr.height));
    }
  },
  computed: {
    uploadCount () {
      return this.commonAttr.uploadCount ? this.commonAttr.uploadCount : 1
    },
    isDisplayDeleteBtn() {
      return isHasOwnProperty(this.commonAttr, 'isDisplayDeleteBtn') ? this.commonAttr.isDisplayDeleteBtn : true
    }
  },
  methods: {
    onDelete() {
      this.updateUploadFormValue();
      let saveEvent = this.item.events.saveImg;
      if(saveEvent) {
        let pushCompId = getCompIdByParam(saveEvent.comps[0].attrs.value)
        if(pushCompId) {
          this.$store.commit("deletePushPicItem", { id: pushCompId, controlId: CONTROL_TYPES.wb_push, fileNames: this.fileNames })
        }
      }
    },
    updateUploadFormValue() {
      let urls = [];
      this.fileNames = [];
      _.forEach(this.fileList, (file_) => {
        urls.push(this.fileUrls[file_.file.name]);
        this.fileNames.push(file_.file.name);
      })
      this.$store.commit("updateFormValue", {
        id: this.item.id,
        urls,
      });
    },
    onAfterRead(file) {
      file.status = "uploading";
      file.message = "上传中...";

      let fileName = file.file.name;
      let suffix = fileName.split(".")[1];
      let base64 = file.content;
      // this.compress(file.file, {
      //   quality: this.commonAttr.saveImgQuality,
      //   width: 750,
      // }, (base64) => {
        this.fileToBlob(
          base64,
          suffix,
          (url) => {
            this.fileUrls[fileName] = url;
            this.item.commonAttr.uploadImgUrl = url;
            this.updateUploadFormValue();
            file.status = "";
            file.message = "";
            let saveEvent = this.item.events.saveImg;
            if(saveEvent) {
              let blob = this.base64ToBlob(base64), pushCompId = getCompIdByParam(saveEvent.comps[0].attrs.value)
              if(pushCompId) {
                this.setUploadParams(blob, base64, pushCompId, fileName)
              }
            }
          },
          () => {
            file.status = "failed";
            file.message = "上传失败";
          })
      // });
    },
    base64ToBlob(dataurl) {
      let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    compress(file, objCompressed, cb) {
      let this_ = this;
      let ready = new FileReader();
      ready.readAsDataURL(file);
      ready.onload = function () {
        let base64 = this.result;
        this_.canvasDataURL(base64, objCompressed, cb);
      };
    },
    canvasDataURL(base64, objCompressed, cb) {
      let img = new Image();
      img.src = base64;
      let that_ = this
      img.onload = function () {
        let that = this;
        //默认压缩后图片规格
        let quality = that_.commonAttr.saveImgQuality ? that_.commonAttr.saveImgQuality : 0.5;
        let w = that.width;
        let h = that.height;
        let scale = w / h;
        //实际要求
        w = objCompressed.width > w ? w : objCompressed.width || w;
        h = objCompressed.height || w / scale;
        if (
          objCompressed.quality &&
          objCompressed.quality > 0 &&
          objCompressed.quality <= 1
        ) {
          quality = objCompressed.quality;
        }
        //生成canvas
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        // 创建属性节点
        let anw = document.createAttribute("width");
        anw.nodeValue = w;
        let anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        let base64 = canvas.toDataURL('image/' + that_.commonAttr.saveImgType, Number(quality));
        // 回调函数返回base64的值
        cb(base64);
      };
    },
    onOversize() {
      this.showToast(`文件大小不能超过${Math.round(this.commonAttr.uploadLimitSize)}M`);
    },
    onBeforeRead(file) {
      if (this.accept.indexOf(file.type) == -1) {
        this.showToast("请上传 jpg/png 格式图片");
        return false;
      }
      return true;
    },
  },
};
</script>

<style lang="scss">
.wb-upload {
  width: inherit;
  height: inherit;
  display: flex;
  align-items: center;
  overflow: hidden;
}
.van-uploader__mask-message {
  padding: 0;
  margin-top: 0;
  font-size: var(--size-8);
  line-height: 1;
}
.van-loading {
  position: relative;
  font-size: 0;
  vertical-align: middle;
}
.van-uploader__upload {
  border-radius: var(--size-8);
}
.van-uploader__preview-delete-icon{
  font-size: var(--size-36);
}
.van-uploader__preview-delete{
  width: var(--size-36);
  height: var(--size-36);
}
.van-uploader__mask{
  width: inherit;
  height: inherit;
}
.uploader-bg {
  width: 100%
}
.van-uploader__upload, .van-uploader__preview-image {
  width: var(--van-uploader-w-size);
  height: var(--van-uploader-h-size);
  margin: 0;
}
</style>
